﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NetMQ;
using NetMQ.Sockets;
using ZHello.MQ;

namespace ZHello.Net.MQ.netmq
{
    internal class NetMQSubClient : ISubClient
    {
        public event EventHandler<DataArgs> OnData;

        private List<string> ConnectingAddrs { get; set; }
        private SubscriberSocket Socket { get; set; }

        public NetMQSubClient(string addr)
        {
            ConnectingAddrs = new List<string>();
            Socket = new SubscriberSocket();
            Socket.Connect(addr);
            ConnectingAddrs.Add(addr.ToLower().Trim());
            Timer = new Timer(TimerWrok, null, 20, 20);
        }

        #region Timer

        private Timer Timer { get; set; }
        private Msg _msg = new Msg();

        private void TimerWrok(object obj)
        {
            Timer.Change(Timeout.Infinite, Timeout.Infinite);
            try
            {
                if (Socket.HasIn)
                {
                    //var str = _msg.GetString(System.Text.Encoding.UTF8);
                    var str = Socket.ReceiveFrameString();
                    if (str != null && OnData != null)
                    {
                        OnData.Invoke(null, new DataArgs(str));
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            Timer.Change(20, 20);
        }

        #endregion Timer

        public void AddExtraAddress(string addr)
        {
            Socket.Connect(addr);
        }

        public void RemoveSubAddress(string addr)
        {
            Socket.Disconnect(addr);
        }

        public void SubcribeAll()
        {
            Socket.Subscribe("");
        }

        public void Subscribe(string prefix)
        {
            Socket.Subscribe(prefix);
        }

        public void UnSubscribe(string prefix)
        {
            Socket.Unsubscribe(prefix);
        }

        public void UnSubscribeAll()
        {
            Socket.Unsubscribe("");
        }

        public void Dispose()
        {
            Socket.Close();
            Socket.Dispose();
        }
    }
}
